<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);
namespace addons\xilumarket\chatprograms\GatewayWorker\Applications\YourApp;

use app\common\model\xilumarket\ChatSession;
use think\Config;
use think\Hook;
use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class MyEvents
{
    /**
     * 当客户端连接上gateway完成websocket握手时触发的回调函数。
     * @param  [type] $client_id [description]
     * @param  [type] $data      [description]
     * @return [type]            [description]
     */
    public static function onWebSocketConnect($client_id, $data)
    {
        $token = $data['get']['token'] ?? '';
        // 当没有用户token时关掉
        if (!$token) {
            Gateway::closeClient($client_id);
            return;
        }

        $result = (new \addons\xilumarket\chatprograms\library\UserAuth)->init($token);
        if (!$result['status']) {
            Gateway::sendToClient($client_id, json_encode([
                'code' => 401,
                'msg' => $result['msg'],
                'type' => 'login',
                'data' => null,
            ]));
            return;
        }
        $upload = \app\common\model\Config::upload();
        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);
        Config::set('upload', array_merge(Config::get('upload'), $upload));

        $userauth = $result['data'];
        Gateway::bindUid($client_id, 'user_' . $userauth->id);
        $_SESSION['user_id'] = $userauth->id;
        // 返回当前用户的未读消息个数，
        // 返回当前表情包所有数组数据。
        // 返回当前用户头像、昵称、id。
        $chat = new \addons\xilumarket\chatprograms\library\Chat();
        $return_data['user_info'] = [
            'user_id' => $userauth->id,
            'nickname' => $userauth->nickname,
            'avatar' => $userauth->avatar,
            'gender' => $userauth->gender,
        ];
        $return_data = array_merge($return_data, $chat->init_data($userauth->id));
        $_SESSION['current_user'] = $return_data['user_info'];
        Gateway::sendToClient($client_id, json_encode([
            'code' => 1,
            'msg' => '请求成功',
            'type' => 'login',
            'data' => $return_data,
        ]));
    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        // 客户端传递的是json数据
        $message_data = json_decode($message, true);
        if (!$message_data) {
            return true;
        }
        if (!isset($_SESSION['user_id']) || !$_SESSION['user_id']) {
            return true;
        }
        // 获取用户id
        $user_id = $_SESSION['user_id'];
        $chat = new \addons\xilumarket\chatprograms\library\Chat();
        $function_name = $message_data['type'];
        if (!method_exists($chat, $function_name)) {
            return;
        }
        $ret = $chat->$function_name($user_id, $message_data);
        if ($ret['code'] == 1 && ($function_name == 'say' || $function_name == 'backmsg')) {
            $receive_user_id = 'user_' . $ret['data']['receive_user_id'];
        }
        if($ret['is_group']) {
            Gateway::sendToGroup('session_'.$ret['session_id'], json_encode($ret));
        }else{
            Gateway::sendToClient($client_id, json_encode($ret));
            // 如果接收人在线，给接收人发
            if ($ret['code'] == 1 && ($function_name == 'say' || $function_name == 'backmsg')) {
                if (Gateway::isUidOnline($receive_user_id)) {
                    $ret['type'] = 'new_msg'; //返回消息类型
                    // 在线就转发消息给对应的uid
                    Gateway::sendToUid($receive_user_id, json_encode($ret));
                }
            }
        }
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
        // 向所有人发送
        // GateWay::sendToAll("$client_id logout\r\n");
    }

}
